local blaze = require "blaze"
local gamelib = require "club.threecard.gamelib"
local app = require "app"

local Vector2 = CS.UnityEngine.Vector2
local Vector3 = CS.UnityEngine.Vector3
local Time = CS.UnityEngine.Time

local M = gamelib.ui.element()

local MAX_DESC = 14
local TIME_NORMAL = 0.5
local TIME_END = 3
local TIME_WAITING = 2

function M:ctor(res)
    self.res = res or "club.threecard.slotlib/fx/common.b:blazetime"
end

function M:show(value, multiple)
    self:super("show", true)

    self.value = value
    self.multiple = multiple
    if self.multiple > MAX_DESC then
        self.multiple = MAX_DESC
    end

    local total_time = (self.multiple - 1) * TIME_NORMAL + TIME_END + TIME_WAITING
    self:lazy("on_show")
    return total_time
end

function M:hide()
    self:super("hide")
    self:stop_all_coroutines()
end

local function on_upgrade(self, stage)
    stage = stage - 1
    if stage > 4 then
        stage = 4
    end
    app.audio.post("slotlib:popup_reward"..stage)
    self.animator:Play("upgrade", 0, 0)
    self.desc_txt.transform:DOPunchScale(Vector3(1.1, 1.1, 1.1), 0.1)
end

local function play(self)
    local total_time = (self.multiple - 1) * TIME_NORMAL + TIME_END
    gamelib.utility.digit(self.value_txt, 0, self.value, app.i18n.styles.chip2, total_time)

    local y = self.progress_bar.sizeDelta.y
    self.progress_bar.sizeDelta = Vector2(0, y)

    local stage = 1
    local x = self.progress_bg.rect.size.x - self.progress_bg.transform.localPosition.x
    local current_scale = 1

    while stage <= self.multiple do
        self.root.transform.localScale = Vector3(current_scale, current_scale, current_scale)
        current_scale = current_scale + 0.1

        if current_scale > 1 then
            on_upgrade(self, stage)
        end

        self.desc_txt.text = app.i18n.text("slot:blaze time " .. stage)
        local time = TIME_NORMAL
        local total_x = x
        if stage == self.multiple then
            time = TIME_END
            total_x = x * math.random(60, 95)/100
        end

        local speed = x/time * Time.deltaTime
        local current_x = 0
        while current_x < total_x do
            current_x = current_x + speed
            if current_x > total_x then
                current_x = total_x
            end
            self.progress_bar.sizeDelta = Vector2(current_x, y)
            blaze.coroutine.step()
        end
        
        stage = stage + 1
    end

    app.audio.post("slotlib:duplicate_start")
    blaze.coroutine.wait(TIME_WAITING)
    self:hide()
end

function M:on_show()
    if not self.value or not self.multiple then
        return
    end
    self:start_coroutine(play, self, state)
end

return M